package com.ding.dailyup.service;

import java.time.LocalDateTime;
import java.util.List;

import com.ding.dailyup.model.StrategyApplication;
import com.ding.dailyup.repository.StrategyApplicationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ding.dailyup.emum.StrategyStatusEnum;
import com.ding.dailyup.exception.BOException;
import com.ding.dailyup.model.StockStrategy;
import com.ding.dailyup.repository.StockStrategyRepository;
import com.google.common.collect.Lists;

@Service
public class StockStrategyService {
	@Autowired
	private StockStrategyRepository stockStrategyRepository;
	@Autowired
	private StrategyApplicationRepository strategyApplicationRepository;

	public List<StockStrategy> listStrategies() {
		return stockStrategyRepository
				.findByStatusNotOrderById(StrategyStatusEnum.DEL.status())
				.orElse(Lists.newArrayList());
	}

	public StockStrategy findById(Long strategyId) {
		return stockStrategyRepository.findById(strategyId)
				.orElseThrow(() -> new BOException("策略不存在!"));
	}

	public List<StockStrategy> findByCategoryId(Long categoryId) {
		return stockStrategyRepository
				.findAllByCategoryIdAndStatusNotOrderBySortKeyDesc(categoryId,
						StrategyStatusEnum.DEL.status())
				.orElse(Lists.newArrayList());
	}

	public List<StockStrategy> listDefaultStrategies() {
		return stockStrategyRepository
				.findAllByStatusOrderBySortKeyDesc(
						StrategyStatusEnum.DEFAULT.status())
				.orElse(Lists.newArrayList());
	}

	public void saveStrategyApplication(String strategyName,
			String strategyContext, String remark, double reward, int runType,
			long userId, String wxId) {
		LocalDateTime now = LocalDateTime.now();
		StrategyApplication strategyApplication = new StrategyApplication(
				strategyName, strategyContext, reward, runType, wxId, userId,
				remark, now, now);

		strategyApplicationRepository.save(strategyApplication);
	}
}
